package com.jn.zhinongbao.adapter;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.viewpager2.widget.ViewPager2;

import com.example.supportingagriculturaltreasures.adapter.MainPagerAdapter;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.example.supportingagriculturaltreasures.fragment.HomeFragment;
import com.example.supportingagriculturaltreasures.utils.PreferenceManager;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity implements HomeFragment.OnSearchClickListener {

    private ViewPager2 viewPager;
    private BottomNavigationView bottomNavigation;
    private EditText etSearch;
    private Button btnBuy;
    private PreferenceManager preferenceManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initViews();
        setupViewPager();
        setupBottomNavigation();
        setupClickListeners();
        
        preferenceManager = new PreferenceManager(this);
        
        // 初始化示例数据
        initSampleData();
    }

    private void initViews() {
        viewPager = findViewById(R.id.view_pager);
        bottomNavigation = findViewById(R.id.bottom_navigation);
        etSearch = findViewById(R.id.et_search);
        btnBuy = findViewById(R.id.btn_buy);
    }

    private void setupViewPager() {
        MainPagerAdapter adapter = new MainPagerAdapter(this);
        viewPager.setAdapter(adapter);
        
        // 禁用ViewPager2的滑动，让用户只能通过底部导航切换
        viewPager.setUserInputEnabled(false);
    }

    private void setupBottomNavigation() {
        bottomNavigation.setOnItemSelectedListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.nav_home) {
                viewPager.setCurrentItem(0);
                return true;
            } else if (itemId == R.id.nav_agriculture) {
                viewPager.setCurrentItem(1);
                return true;
            } else if (itemId == R.id.nav_publish) {
                viewPager.setCurrentItem(2);
                return true;
            } else if (itemId == R.id.nav_message) {
                viewPager.setCurrentItem(3);
                return true;
            } else if (itemId == R.id.nav_profile) {
                viewPager.setCurrentItem(4);
                return true;
            }
            return false;
        });

        // 设置默认选中首页
        bottomNavigation.setSelectedItemId(R.id.nav_home);
    }

    private void setupClickListeners() {
        btnBuy.setOnClickListener(v -> {
            Toast.makeText(this, "去卖货功能开发中...", Toast.LENGTH_SHORT).show();
        });

        etSearch.setOnClickListener(v -> {
            startSearchActivity();
        });
    }

    private void startSearchActivity() {
        Intent intent = new Intent(this, SearchActivity.class);
        startActivity(intent);
    }

    @Override
    public void onSearchClick() {
        startSearchActivity();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_logout) {
            showLogoutConfirmDialog();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 显示退出登录确认对话框
     */
    private void showLogoutConfirmDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("退出登录")
                .setMessage("确定要退出登录吗？")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        performLogout();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setCancelable(true)
                .show();
    }

    /**
     * 执行退出登录操作
     */
    private void performLogout() {
        try {
            // 获取当前用户名
            String username = preferenceManager.getCurrentUsername();
            if (username == null || username.isEmpty()) {
                username = "用户";
            }
            
            // 清除登录信息
            preferenceManager.clearUserLogin();
            
            // 跳转到登录页面，携带退出登录信息
            Intent intent = new Intent(this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.putExtra("fromLogout", true);
            intent.putExtra("logoutMessage", "再见，" + username + "！");
            startActivity(intent);
            
            // 结束当前Activity
            finish();
            
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "退出登录失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 处理返回键，显示退出确认
     */
    @SuppressLint("MissingSuperCall")
    @Override
    public void onBackPressed() {
        showExitConfirmDialog();
    }

    /**
     * 显示退出应用确认对话框
     */
    private void showExitConfirmDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("退出应用")
                .setMessage("确定要退出农业宝藏应用吗？")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setPositiveButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 退出应用
                        finishAffinity();
                        System.exit(0);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setNeutralButton("退出登录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        performLogout();
                    }
                })
                .setCancelable(true)
                .show();
    }

    /**
     * 初始化示例数据
     */
    private void initSampleData() {
        new Thread(() -> {
            try {
                DatabaseHelper databaseHelper = new DatabaseHelper(this);
                // 创建示例新闻数据
                databaseHelper.createSampleNewsData();
                databaseHelper.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}